package com.yvon.maple.service.msg.core.service.impl;

import com.yvon.boot.mybatis.BaseServiceImpl;
import com.yvon.maple.cloud.web.filter.LoginUserUtil;
import com.yvon.maple.service.msg.core.model.entity.ImConsumer;
import com.yvon.maple.service.msg.core.mapper.ImConsumerMapper;
import com.yvon.maple.service.msg.core.service.ImConsumerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : Yvon
 * @since : 2021-08-26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ImConsumerServiceImpl extends BaseServiceImpl<ImConsumer, ImConsumerMapper> implements ImConsumerService {

    @Override
    public boolean save(Long messageId, Set<String> consumers) {
        return saveBatch(consumers
                .stream()
                .map(userId -> ImConsumer.builder()
                        .messageId(messageId)
                        .read(false)
                        .userId(Long.valueOf(userId))
                        .build()
                )
                .collect(Collectors.toList())
        );
    }

    @Override
    public boolean markRead(Set<Long> consumerIds) {
        return lambdaUpdate()
                .set(ImConsumer::getReadTime, LocalDateTime.now())
                .set(ImConsumer::getRead, true)
                .in(ImConsumer::getId, consumerIds)
                .eq(ImConsumer::getRead, false)
                .update();
    }


    @Override
    public boolean markUnRead(Set<Long> consumerIds) {
        return lambdaUpdate()
                .set(ImConsumer::getReadTime, LocalDateTime.now())
                .set(ImConsumer::getRead, false)
                .in(ImConsumer::getId, consumerIds)
                .eq(ImConsumer::getRead, true)
                .update();
    }
}
